package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient client;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;


    @Override
//    @Async
    public void autoScanWmNews(Integer id) throws Exception {
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(null == wmNews){
            throw  new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //抽取文章中的文本数据和图片数据
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            Map<String,Object> textAndImages = handleTextAndImages(wmNews);

            //自管理敏感词过滤
            boolean isSensitive = handleSensitiveScan((String) textAndImages.get("textContent"),wmNews);
            if(!isSensitive) return;

            //发送文本到阿里云进行审核,返回是否通过
            boolean isTextScan = handleTextScan((String) textAndImages.get("textContent"),wmNews);
            if(!isTextScan)return;

            //发送图片数据给阿里云进行审核,不通过返回审核状态和原因
            boolean isImageScan =  handleImageScan((List<String>) textAndImages.get("images"),wmNews);
            if(!isImageScan)return;

            //调用feign请求完成数据同步
            ResponseResult responseResult = saveAppArticle(wmNews);

            int i =1/0;

            //跟新文章状态
            if(!responseResult.getCode().equals(200)){
                throw  new CustomException(AppHttpCodeEnum.SERVER_ERROR);
            }

            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNewStatus(wmNews,(short) 9,"审核成功");

        }



    }

    private boolean handleSensitiveScan(String textContent, WmNews wmNews) {
        boolean flag =true;
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(item -> item.getSensitives().toString()).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(textContent);
        if(map.size()>0){
            updateWmNewStatus(wmNews, (short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }
        return flag;
    }

    private ResponseResult saveAppArticle(WmNews wmNews) {
        /*ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        dto.setAuthorId(wmNews.getUserId());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }
        String channelId = wmChannelMapper.selectById(wmNews.getChannelId()).getName();
        dto.setChannelName(channelId);
        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());*/
        ArticleDtoBuilder builder = new ArticleDtoBuilder(wmNews,wmChannelMapper,wmUserMapper);
        ArticleDto dto = builder.buildBeanCopy().buildBasic().buildChannel().buildAuthor().builder();
        ResponseResult responseResult = client.saveArticle(dto);
        return responseResult;
    }

    private boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        boolean flag = true;
        if(null == images||images.size() == 0){
            return flag;
        }
        images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList = new ArrayList<>(images.size());
        for (String image : images) {
            byte[] bytes = fileStorageService.downLoadFile(image);
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            BufferedImage imageFile = ImageIO.read(in);
            String result = tess4jClient.doOCR(imageFile);
            boolean isSensitive = handleSensitiveScan(result, wmNews);
            if(!isSensitive) {
                return isSensitive;
            }
            imageList.add(bytes);
        }
        Map map = greenImageScan.imageScan(imageList);
        if(null != map){
            if("block".equals(map.get("suggestion"))){
                updateWmNewStatus(wmNews,(short)2,"图片中存在违规内容");
                flag = false;
            }else if("review".equals(map.get("suggestion"))){
                updateWmNewStatus(wmNews,(short)2,"图片中存在不确定因素需要人工进行审核");
                flag = false;
            }
        }
        return flag;
    }

    private boolean handleTextScan(String content, WmNews wmNews) throws Exception {
        Boolean flag = true;
        Map map = greenTextScan.greeTextScan(content);
        if(null != map){
            if("block".equals(map.get("suggestion"))){
                updateWmNewStatus(wmNews,(short)2,"文本中存在违规内容");
                flag = false;
            }else if("review".equals(map.get("suggestion"))){
                updateWmNewStatus(wmNews,(short)2,"不确定因素需要人工进行审核");
                flag = false;
            }
        }
        return flag;
    }

    private void updateWmNewStatus(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        StringBuffer sb = new StringBuffer();
        List<String> images = new ArrayList<>();
        if(StringUtils.isNotEmpty(wmNews.getContent())){
            List<Map> list = JSON.parseArray(wmNews.getContent(),Map.class);
            for (Map map : list) {
                if("image".equals(map.get("type"))){
                    images.add(map.get("value").toString());
                }else if ("text".equals(map.get("type"))){
                    sb.append(map.get("value").toString());
                }
            }
        }
        sb.append(wmNews.getTitle());
        if(StringUtils.isNotEmpty(wmNews.getImages())){
            String[] imgs = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(imgs));
        }
        Map<String,Object> map = new HashMap<>();
        map.put("textContent",sb.toString());
        map.put("images",images);
        return map;

    }
}